import { useStorage } from '@vueuse/core';
import { defineStore } from 'pinia';
import { store } from '@/store';
import router from '@/router';
import LoginAPI from '@/api/admin/login';

const Layout = () => import('@/layout/index.vue');
const BlankLayout = () => import('@/layout/blank.vue');
const modules = import.meta.glob('../../views/**/*.vue');

export const usePermissionStore = defineStore('permission', () => {
  // menuRoutes: 从后端获取的原始菜单数据，持久化存储
  const menuRoutes = useStorage('menu_routes', []);
  // 用于跟踪所有被动态添加的路由;
  const addRoutes = ref([]);
  // mixLeftMenus: 混合菜单的左侧部分
  const mixLeftMenus = ref([]);
  // 动态路由是否已生成
  const isRouteGenerated = ref(false);
  async function generateRoutes(nolayout = false) {
    try {
      const { data } = await LoginAPI.getRoutes();
      console.log('[modules.permission.js] loading data');
      // 从后端直接获取处理好的数据
      const backendRouterData = data.routerData;
      // 存储菜单数据
      menuRoutes.value = data.menuData;
      // 前端只需进行简单的组件映射
      const accessibleRoutes = transformRoutes(backendRouterData, nolayout);
      // 将转换后的动态路由保存到 addRoutes state 中
      addRoutes.value = accessibleRoutes;
      // 标记动态路由已生成
      isRouteGenerated.value = true;
      // 将动态路由添加到 router 实例中
      accessibleRoutes.forEach((route) => {
        router.addRoute(route);
      });
      return accessibleRoutes;
    } catch (error) {
      console.error('Failed to generate routes:', error);
      isRouteGenerated.value = false;
    }
  }
  // 无需刷新的路由重置方法
  function resetRouter() {
    addRoutes.value.forEach((route) => {
      if (route.name && router.hasRoute(route.name)) {
        router.removeRoute(route.name);
        console.log(`路由 '${route.name}' 已被移除。`);
      }
    });
    addRoutes.value = [];
    menuRoutes.value = [];
  }

  function setMixLeftMenus(topMenuPath) {
    const matchedItem = menuRoutes.value.find(
      (item) => item.path === topMenuPath,
    );
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  }

  return {
    menuRoutes,
    addRoutes,
    isRouteGenerated,
    routes: menuRoutes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
    resetRouter,
  };
});

/**
 * 将后端返回的路由数据中的 component 字符串，转换为真正的组件
 * @param {Array} routes - 后端返回的 routerData
 * @param {boolean} nolayout - 是否禁用布局
 */
function transformRoutes(routes, nolayout = false) {
  const result = [];
  for (const route of routes) {
    const tmpRoute = { ...route };

    // 1. 处理顶层组件 (Layout 或 非Layout)
    if (tmpRoute.component === 'Layout') {
      tmpRoute.component = nolayout ? BlankLayout : Layout;
    } else {
      tmpRoute.component = resolveComponent(tmpRoute.component);
    }

    // 2. 处理 children 里的业务组件
    if (tmpRoute.children) {
      tmpRoute.children = tmpRoute.children.map((child) => {
        return {
          ...child,
          component: resolveComponent(child.component),
        };
      });
    }
    result.push(tmpRoute);
  }
  return result;
}

/**
 * 辅助函数：根据路径字符串加载组件
 */
function resolveComponent(componentPath) {
  const absolutePath = `../../views/${componentPath}.vue`;
  const component = modules[absolutePath];
  if (component) {
    return component;
  }
  console.error(`Component not found for path: ${componentPath}`);
  return modules['../../views/admin/base/error/404.vue'];
}

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
